package com.ld.zookeeper.api;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author:ld
 * @create:2020-04-21 12:23
 * @description: zookeeper 原生API创建节点
 * 事件类型
 * EventType
 *  None(-1),
 *  NodeCreated(1),
 *  NodeDeleted(2),
 *  NodeDataChanged(3),
 *  NodeChildrenChanged(4);
 *
 * 连接状态
 * KeeperState
 *  Disconnected(0),
 *  SyncConnected(3),
 *  AuthFailed(4),
 *  ConnectedReadOnly(5),
 *  SaslAuthenticated(6),
 *  Expired(-112);
 *
 *
 */
public class ZookeeperCreate {

    //连接对象
    private ZooKeeper zooKeeper;

    //连接地址
    private final String IP = "127.0.0.1:2181";

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) {

    }

    /**
     * 开启连接
     */
    @Before
    public void befor() throws IOException, InterruptedException {
        //创建连接，因为是异步连接的，需要等待连接成功才能使用
        // arg1：连接地址
        // arg2：超时时间
        // arg3：自定义监视器
        zooKeeper = new ZooKeeper(IP, 5000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                //连接成功
                if(Event.KeeperState.SyncConnected.equals(watchedEvent.getState())){
                    countDownLatch.countDown();
                    System.out.println("连接成功......");
                }else if(Event.KeeperState.Disconnected.equals(watchedEvent.getState())){
                    System.out.println("连接失败......");
                }else if(Event.KeeperState.AuthFailed.equals(watchedEvent.getState())){
                    System.out.println("用户认证失败......");
                }
            }
        });
        //等待连接成功
        countDownLatch.await();
    }

    /**
     * 关闭连接
     * @throws InterruptedException
     */
    @After
    public void after() throws InterruptedException {
        zooKeeper.close();
    }

    /**
     * 同步创建节点
     */
    @Test
    public void create1() throws KeeperException, InterruptedException {
        // arg1：节点路径
        // arg2：节点数据
        // arg3：访问控制列表（ACL） ZooDefs.Ids.OPEN_ACL_UNSAFE ：world:anyone:rwcda
        // arg4：节点类型
        //      PERSISTENT(0, false, false),
        //      PERSISTENT_SEQUENTIAL(2, false, true),
        //      EPHEMERAL(1, true, false),
        //      EPHEMERAL_SEQUENTIAL(3, true, true);
        // return ：节点名称
        String result = zooKeeper.create("/create1", "create1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(result + " 创建成功......");
    }

    /**
     * 异步创建节点
     * @throws InterruptedException
     */
    @Test
    public void create2() throws InterruptedException {
        // 前四个参数已经介绍过了
        // arg5：异步接口
        // arg6：上下文对象
        zooKeeper.create("/create2", "create2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new AsyncCallback.StringCallback() {
            @Override
            public void processResult(int i, String s, Object o, String s1) {
                //返回结果，如果为0为成功
                System.out.println(i);
                //节点路径
                System.out.println("节点路径：" + s);
                //上下文对象
                System.out.println("上下文对象：" + o);
                //节点名称
                System.out.println("节点名称：" + s1);
            }
        },"I am context");
        Thread.sleep(3000);
        System.out.println("结束");
    }
}
